package com.freedom.sql.jdbc.request;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSetNamesStatement;
import com.freedom.sql.jdbc.netty.MyNioSocketChannel;
import com.freedom.sql.jdbc.response.CommonOkPacket;
import com.freedom.sql.jdbc.utils.CharsetUtils;
import com.freedom.sql.jdbc.utils.LoggerUtils;

public class SetNamesPacket {
	private static final Logger logger = LogManager.getLogger(SetNamesPacket.class);
	private MyNioSocketChannel channel;
	private MySqlSetNamesStatement statement;
	private int packetSeq;

	public SetNamesPacket(int _packetSeq, MyNioSocketChannel _channel, MySqlSetNamesStatement _statement) {
		packetSeq = _packetSeq;
		channel = _channel;
		statement = _statement;
	}

	public void read() throws Exception {
		// 提取出内容--->charset & index
		String charset = statement.getCharSet();
		;
		int ci = CharsetUtils.getIndex(charset);
		// 合法的charset
		if (ci > 0) {
			channel.setCharset(charset);
			channel.setCharsetIndex(ci);
			LoggerUtils.debug(logger, "set charset to be ==" + charset);
			// 发送成功命令
			new CommonOkPacket(channel, packetSeq + 1).write();
		} else {
			// 失败则发送失败命令
			throw new Exception("Unknown charset '" + charset + "'");
		}

	}

	// 写
	private Socket writeSocket;
	private String charset;

	public SetNamesPacket(Socket _socket, String _charset) {
		this.writeSocket = _socket;
		this.charset = _charset;
	}

	public void write() throws IOException {
		OutputStream out = writeSocket.getOutputStream();
		out.write(new byte[] { 0x0f, 0x00, 0x00 });
		out.write(new byte[] { 0x00 });
		out.write(new byte[] { 0x03 });// query
		out.write(("SET NAMES " + charset).getBytes());
		out.flush();
	}

}
